/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dac.h"
#include "rtc.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "string.h"
#include "led.h"
#include "key.h"
#include "lcd.h"
#include "i2c.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

//流水灯执行程序
__IO uint32_t ledTick = 0;
uint8_t led_ctrl = 0xff;
void LED_Process(void)
{
    if(uwTick - ledTick<500)return;
    ledTick = uwTick;
    LED_Control(led_ctrl);
    led_ctrl = ~led_ctrl;
}

//按键执行程序
__IO uint32_t keyTick = 0;
void Key_Process(void)
{
    if(uwTick - keyTick < 10)return;
    keyTick = uwTick;
    Key_Read();
    if(Trg & 0x01){ LED_Control(0x01);}
    if(Trg & 0x02){ LED_Control(0x02);}
    if(Trg & 0x04){ LED_Control(0x04);}
    if(Trg & 0x08){ LED_Control(0x08);}
}

// ADC
float volt_r37,volt_r38,volt_mcp;
void ADC_Process(void)
{
    //Rank1 - CH5
    HAL_ADC_Start(&hadc1);
    volt_mcp = (float )HAL_ADC_GetValue(&hadc1)/4096.0f*3.3f;

    //Rank2 - CH11
    HAL_ADC_Start(&hadc1);
    volt_r38 = (float )HAL_ADC_GetValue(&hadc1)/4096.0f*3.3f;

    HAL_ADC_Start(&hadc2);
    volt_r37 = (float )HAL_ADC_GetValue(&hadc2)/4096.0f*3.3f;
}


//RTC执行程序
RTC_TimeTypeDef rtc_time;
RTC_DateTypeDef rtc_data;
void RTC_Process(void)
{
    HAL_RTC_GetTime(&hrtc,&rtc_time,RTC_FORMAT_BIN);
    HAL_RTC_GetDate(&hrtc,&rtc_data,RTC_FORMAT_BIN);
}

//EEPROM
uint8_t val_24c02=0;
uint8_t startup_times=0;
//MCP4017
u8 val_mcp=0;

//DAC
uint16_t dac_ch1_val,dac_ch2_val;
void DAC_Process(void)
{
    dac_ch1_val = (uint16_t)(1.1f/3.3f*4095);
    dac_ch2_val = (uint16_t)(2.5f/3.3f*4095);

    HAL_DAC_SetValue(&hdac1,DAC_CHANNEL_1,DAC_ALIGN_12B_R,dac_ch1_val);     //0-->0v    4095-->3,3v
    HAL_DAC_Start(&hdac1,DAC_CHANNEL_1);

    HAL_DAC_SetValue(&hdac1,DAC_CHANNEL_2,DAC_ALIGN_12B_R,dac_ch2_val);     //0-->0v    4095-->3,3v
    HAL_DAC_Start(&hdac1,DAC_CHANNEL_2);
}

//串口接收执行程序
uint8_t usart_buf[2];
uint8_t rx_buf[10];
uint8_t rx_cnt = 0;
__IO uint32_t uartTick = 0;
void RxIdle_Process(void)
{
    if(uwTick - uartTick < 50)return;
    uartTick = uwTick;
    //50ms执行一次
    rx_cnt =0;
    memset(rx_buf,'\0',sizeof (rx_buf));    //清空接收缓存数组
}

//LCD执行程序
void LCD_Process(void)
{
    u8 display_buf[20];
    sprintf((char*)display_buf,"EEPROM: %3d",startup_times);
    LCD_DisplayStringLine(Line0,display_buf);

    sprintf((char*)display_buf,"MCP:%5.2f",volt_mcp);
    LCD_DisplayStringLine(Line2,display_buf);

    sprintf((char*)display_buf,"R37:%5.2f R38:%5.2f",volt_r37,volt_r38);
    LCD_DisplayStringLine(Line3,display_buf);

    sprintf((char*)display_buf,"Time: %02d-%02d-%02d",rtc_time.Hours,rtc_time.Minutes,rtc_time.Seconds);
    LCD_DisplayStringLine(Line5,display_buf);
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  MX_RTC_Init();
  MX_ADC1_Init();
  MX_ADC2_Init();
  MX_DAC1_Init();
  MX_TIM16_Init();
    HAL_TIM_PWM_Start(&htim16,TIM_CHANNEL_1);
    TIM16->ARR = 49;	// 周期是50us，对应频率20kHz
    TIM16->CCR1 = 10; // 20%占空比
  MX_TIM17_Init();
    HAL_TIM_PWM_Start(&htim17,TIM_CHANNEL_1);
    TIM17->ARR = 499;	// 周期是500us，对应频率2kHz
    TIM17->CCR1 = 400; // 80%占空比


  /* USER CODE BEGIN 2 */
    HAL_UART_Receive_IT(&huart1,usart_buf,1);    //开启串口接收中断
    LCD_Init();
    I2CInit();
    LED_Control(0x00);

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */


    LCD_Clear(Blue);
    LCD_SetBackColor(Blue);
    LCD_SetTextColor(White);
  //串口发送
    printf("Hello World!\r\n");
    printf("N: %d \r\n",123);
    printf("N: %f \r\n",3.1415);

    //EEPROM
    startup_times = EEPROM_Read(0x20);
    EEPROM_Write(0x20,startup_times+1);
    //MCP4017
    MCP4017_Write(0x7f);
    val_mcp = MCP4017_Read();
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
    //串口接收固定长度数据
      LED_Process();
      Key_Process();
      ADC_Process();
      DAC_Process();
      RTC_Process();
      LCD_Process();
      RxIdle_Process();

  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);
  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI|RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV3;
  RCC_OscInitStruct.PLL.PLLN = 20;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
/*串口接收回调函数*/
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    uartTick = uwTick;      //重新开始计时50ms
    //接收3个字节长度数据 ,rx_buf[0]写入EEPROM, rx_buf[1]控制LED.
    rx_buf[rx_cnt++] = usart_buf[0];
    if(usart_buf[0]== '\n')     //接收到换行符 \r\n
    {
        rx_cnt=0;
        LED_Control(rx_buf[1]);
    }
    HAL_UART_Receive_IT(&huart1,usart_buf,1);    //开启下一次串口接收
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

